function b64toBlob(data) {
  var sliceSize = 512;
  var chars = atob(data);
  var byteArrays = [];
  for (var offset = 0; offset < chars.length; offset += sliceSize) {
    var slice = chars.slice(offset, offset + sliceSize);
    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    var byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, {
    type: "",
  });
}

/**
 * 导出excel
 * @param {*} param
 * param{
 *     filename:'',
 *     table:'<table><tr><td>1</td></tr></table>',
 *     worksheet:''
 * }
 */
export const toExcel = (param) => {
  var filename = null;
  var worksheet = "Worksheet";
  var times = new Date().getTime();
  if (typeof param == "string") {
    filename = param + times + ".xls";
  } else {
    filename = param["filename"] + times + ".xls";
    worksheet = param["worksheet"] || "Worksheet";
  }
  var uri = "data:application/vnd.ms-excel;base64,",
    template =
      '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{table}</body></html>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      });
    };

  var table = param.table;
  var ctx = {
    worksheet: worksheet,
    table: table,
  };
  var data = base64(format(template, ctx));
  if (window.navigator.msSaveBlob) {
    var blob = b64toBlob(data);
    window.navigator.msSaveBlob(blob, filename);
  } else {
    var alink = document.createElement("a");
    alink.setAttribute("href", uri + data);
    alink.setAttribute("download", filename);
    document.getElementsByTagName("body")[0].appendChild(alink);
    alink.click();

    alink.remove();
  }
};
